import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
// import Home from '../views/home/Home.vue'
// import Center from '../views/center/Center.vue'
import RoutesConfig from './config'
import store from '@/store'

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login
  },
  {
    path: '/mainbox',
    name: "mainbox",
    component: MainBox
  }
  // mainbox的嵌套路由，后面根据权限动态添加
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.name === "login") {
    next();
  } else {
    //如果授权（已经登录） next()
    if (!localStorage.getItem("token")) {
      next({
        path: "/login"
      })
    } else {
      
      // next({
        //   path:to.path
        // })
        //next()
        if(!store.state.isGetterRouter){
         ConfigRouter();
         next(
          {
          path: to.fullPath
         }
         )
       }else{
         next()
       }
    }
  }
})
// router.addRoute("mainbox",{
//   path: "/index",
//   component: Home
// })

// router.addRoute("mainbox",{
//   path: "/center",
//   component: Center
// })


const ConfigRouter= ()=>{
  RoutesConfig.forEach(item=>{
     router.addRoute("mainbox",item);
  })
  store.commit("changeGetterRouter",true)
}

export default router
